<template>
	<view class="container">
		<view class="up" v-show="isBack">
			<view class="popup" style="line-height: 65px; text-align: center; font-size: 25px;">
				<text style="text-decoration: underline; color: #007AFF; font-size: 28px;" @click="save()">请点击更新app</text>
			</view>
			<view v-show="isDownload" class="uni-padding-wrap uni-common-mt progress-body">
				<view class="progress-box">
					<progress :percent="progress" show-info stroke-width="3" />
				</view>
			</view>
		</view>
		<view class="loading-indicator">
			<text></text>
		</view>
		<view class="head-in" @click="runningTap">
			<text class="run-count">
				{{runningDistance}}
				<text class="run-company">KM</text>
			</text>
			<text class="run-target">目标：{{homeInfo.rkm}}KM</text>
		</view>
		<view class="main">
			<view class="main-speed">
				<image src="../../static/image/homeimage/run.png" mode=""></image>
				<text class="main-title">配速</text>
				<text class="main-content">{{speed}}km/h</text>
			</view>
			<view class="main-time">
				<image src="../../static/image/homeimage/time.png" mode=""></image>
				<text class="main-title">用时</text>
				<text class="main-content">{{time}}</text>
			</view>
			<view class="main-count">
				<image src="../../static/image/homeimage/remind.png" mode=""></image>
				<text class="main-title">本周完成</text>
				<text class="main-content">{{homeInfo.count}}(次)</text>
			</view>
		</view>
		<view class="foot">
			<view class="foot-start"  v-if="!isRunning" @click="$noMultipleClicks(running)"  >
				<image src="../../static/image/homeimage/start.png"></image>
			</view>
			<view class="foot-start"  v-else @click="running" @longpress="stopRunning" >
				<image  src="../../static/image/homeimage/stop.png"></image>
			</view>
		</view>
	</view>
</template>
<script>
	import homeApi from '../../http/api/home.js'
	import user from '../../http/api/user.js'
	var userId = {}
	var wid = ""
	let startPoint = {
		latitude :'',
		longitude : ''
	}
	let stopPoint = {
		latitude : '',
		longitude : ''
	}
	export default {
		data() {
			return {
				/* 首页信息 */
				homeInfo: {},
				/* 是否正在跑步 */
				isRunning: false,
				/* 能否进行跑步 */
				checkRunning: false,
				speed : "0.00" ,
				time : "00:00:00",
				runningDistance: "0.00",
				timeInt:"",
				speedInt:"",
				/* 显示更新信息的状态 */
				isBack : this.$store.state.isBack,
				progress:"0",
				isDownload:false,
				isTimes:'',
				msg:'',
				rweek:'',
				noClick:true
			}
		},
		onLoad() {
			const that = this;
			uni.$on('running',(msg)=>{
				this.running();
			}); 
			uni.$on('pauseRunning',(msg)=>{
				this.pauseRunning();
			}); 
			uni.$on('stopRunning',(msg)=>{
				this.stopRunning();
			}); 
			uni.getStorage({
				key: 'userInfo',
				/* 无登录信息则跳回登录 */
				fail() {
					uni.redirectTo({
						url: '../login/login'
					})
				},
				success(res) {
					/* 判断是否有关键信息 */
					if (res.data.hasLogin!=undefined&&res.data.snum!=undefined&&res.data.clid!=undefined&&res.data.userId!=undefined) {
						that.$store.commit("saveUser",res.data)
					} else {
						uni.redirectTo({
							url: '../login/login'
						})
					}
				}
			});
		},
		onReady() {
			const that = this;
			userId = {sid: ""};
			/* 获取当前周信息 */
			user.currentSemester().then(res=>{
				let currentSemester = res.data.data.rSemester;
				let currentWeek = res.data.data.week;
				wid = currentWeek.wid;
				that.$store.commit('saveCurrentWeek',currentWeek);
				that.$store.commit('saveCurrentSemester',currentSemester);
				uni.getStorage({
					key:"userInfo",
					success(data){
						userId.sid = data.data.userId;
						that.initData();
						that.notification();
					}
				});
			});
			that.cacheLoading();
		},
		onShow() {
			const that = this;
			// #ifdef APP-PLUS
			/* 判断版本更新信息 */
			plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) { 
			  uni.request({ 
			    url: 'http://111.75.252.147:8083/Runing/rVersion/selectMobileVersion', 
			    data: { 
			      version: widgetInfo.version, 
			      name: widgetInfo.name
			    }, 
			    success: (result) => {
			      var currentVersion = result.data.data.data.version;
				  //------------------------------------------------------------------------
			      if (widgetInfo.version != currentVersion) {
				  //------------------------------------------------------------------------
					  that.$store.commit("saveBackState",true);
					  that.isBack = that.$store.state.isBack;
			      }else{
					  that.$store.commit("saveBackState",false);
					  that.isBack = that.$store.state.isBack;
				  }
			    } 
			  }); 
			}); 
			// #endif
		},
		onBackPress() {
			return this.isBack
		}, 
		methods: {
			/* 判断是否能跑步（方法）包括初始化数据 */
			initData() {
				const that = this;
				var data = {
					sid: userId.sid,
					wid: wid
				}
				homeApi.selectMobileRun(data).then(res => {
					if(res.data.code == 200 ){
						that.homeInfo = res.data.data;
						that.isTimes = res.data.data.count;
						that.rweek = res.data.data.rweek;
						that.$store.commit('saveRweek',that.rweek);
						that.$store.commit('saveRunningTimes',res.data.data.count);
					}else{
						uni.showToast({
							title: '请求失败，请重试',
							icon: 'none',
							duration: 1000
						})
					}
				}).catch(err=>{
					uni.showToast({
						title: err,
						icon: 'none',
						duration: 1000
					})
				})
			},
			/* 跑步方法 */
			running() {
				const that = this;
				homeApi.judgeTime().then(res => {
					if (res.data.code != 200) {
						that.checkRunning = false;
						that.msg = res.data.msg;
						test();
					} else {
						that.checkRunning = true;
						that.msg = res.data.msg;
						test();
					}
				})
				function test(){
					if(!(userId.sid && wid)){
						uni.showToast({
							title: '缺失数据无法跑步，请重新登录app再试',
							icon: 'none',
							duration: 1500
						})
					}else if (!that.isRunning) {
						if(!that.checkRunning){
							uni.showToast({
								title:that.msg,
								icon:'none',
								duration:1500
							})
						}else if(that.isTimes>=that.rweek){
							uni.showToast({
								title:'本周跑步次数已达标，请下周继续',
								icon:'none',
								duration:1500
							});
						}else{
							uni.getLocation({
								success(res) {
									startPoint.latitude = res.latitude.toFixed(6)
									startPoint.longitude =  res.longitude.toFixed(6)
									// if(true){
									if(startPoint.longitude>114.894507&&startPoint.longitude<114.899074&&startPoint.latitude>25.774096&&startPoint.latitude<25.777591){
										console.log("保存第一个定位点");
										console.log(startPoint.longitude+ "      "+startPoint.latitude +"   "+"true")
										console.log("114.894507" +"           "+"114.899074")
										console.log("25.774096" +"           "+"25.777591")
										that.$store.commit('saveStartPoint',startPoint);
										that.timing();
										uni.navigateTo({
											url: 'running/running'
										})
										that.isRunning = !that.isRunning;
										uni.showToast({
											title: '开始跑步',
											duration: 1000,
											icon:'none',
										});
										if(that.$store.state.preLoadState){
											uni.$emit('startLocate',{msg:"startLocate"});
										}else{
											uni.preloadPage({url: "/pages/running/runner/runner"});
										}
									}else{
										uni.showToast({
											icon:"none",
											title:"请在规定区域内跑步!",
											duration:2000
										})
									}
								},
								fail(err) {
									uni.showToast({
										title: "请检查是否打开定位权限和网络",
										duration: 1000,
										icon: 'none'
									})
								}
							})
						}
					}else{
						uni.showToast({
							title: '请长按结束跑步',
							duration: 2000,
							icon: 'none'
						});
					}
				}
				
			},
			/* 暂停跑步方法 */
			pauseRunning(){
				//清除计时器，保留数据
				// time  distance  speed 
				clearInterval(this.timeInt);
				clearInterval(this.speedInt);
				this.isRunning = !this.isRunning;
				uni.$emit('pauseLocate',{msg:"pauseLocate"});
			},
			/* 停止跑步方法 */
			stopRunning(){
				const that = this;
				//截取时间的分钟
				var hour = parseInt(that.time.substring(0,2));
				var minute = parseInt(that.time.substring(3,5));
				var totalMinute = hour*60 + minute;
				uni.getLocation({
					success(res) {
						stopPoint.latitude = res.latitude.toFixed(6)
						stopPoint.longitude =  res.longitude.toFixed(6)
						if(totalMinute<10){
							// if(false){
							uni.showToast({
								title: '跑步时间小于10分钟，请继续跑步',
								icon: 'none',
								duration: 1000
							})
						// }else if(1){
						}else if(stopPoint.longitude>114.894507&&stopPoint.longitude<114.899074&&stopPoint.latitude>25.774096&&stopPoint.latitude<25.777591){
							if(startPoint.longitude>114.894507&&startPoint.longitude<114.899074&&startPoint.latitude>25.774096&&startPoint.latitude<25.777591){
								
							}else{
								startPoint.latitude = stopPoint.latitude.toFixed(6)
								startPoint.longitude =  stopPoint.longitude.toFixed(6)
								that.$store.commit('saveStartPoint',startPoint);
								console.log(that.$store.state.point);
							}
							uni.showModal({
							    title: '结束跑步',
							    content: '确定结束本次跑步吗？',
							    success: function (res) {
							        if (res.confirm) {
										//保存本次运动记录
										var data = {
										    mileage: parseInt(that.runningDistance*1000),
										    runtime: that.time,
										    sid: userId.sid,
											wid: wid
										};
										homeApi.commitData(data).then(res => {
											uni.showLoading({
												title:"成绩上传中...",
											})
											setTimeout(()=>{
												if(res.data.code!=200){
													uni.hideLoading();
													uni.showToast({
														title: res.data.msg ,
														duration: 2000,
														icon:"none"
													});
												}else{
													uni.hideLoading();
													that.initData();
													uni.showToast({
														title: "成绩上传成功",
														duration: 2000
													});
													clearInterval(that.timeInt);
													var time = '00:00:00';
													that.$store.commit("saveTime",time);
													that.time = time;
													that.runningDistance = "0.00";
													that.speed = "0.00"
													var stopState =  true;
													that.$store.commit("saveStopState",stopState);
													that.isRunning = false;
													uni.$emit('stopLocate',{msg:"stopLocate"});
													uni.removeStorage({
													    key: 'statisticInfo'
													});
													that.$store.commit('cleanStatistic');
													//初始化record页面的数据
													uni.$emit("initData");
												}
											},1000)
										}).catch(err=>{
											uni.showToast({
												title: "数据提交失败，请重试或反馈!",
												icon:'none',
												duration:1500
											})
										})
							        } else if (res.cancel) {
										var stopState =  false;
										that.$store.commit("saveStopState",stopState);
							        }
							    }
							});
						}else{
							uni.showToast({
								title: '未在规定区域结束，无法提交',
								icon: 'none',
								duration: 1000
							})
						}
					},
					fail() {
						uni.showToast({
							title:'结束点获取失败 ，请重试',
							icon: 'none',
							duration:1000
						})
					}
				})
			},
			/* 全局定时器方法 */
			timing(){
				let that = this;
				let count = 0;
				if(that.$store.state.time != '00:00:00' ){
					var hour = that.$store.state.time.substring(0,2);
					var minute = that.$store.state.time.substring(3,5);
					var second = that.$store.state.time.substring(6,8);
				}else{
					var hour,second,minute;
					hour = '00';
					minute = '00';
					second = '00';
				}
				that.timeInt =  setInterval(timer,1000);
				//计时方法
				function timer(){
					second++;
					// second +=59;
					if(second>=60){
						second=0;
						minute=parseInt(minute)+1;
						minute = minute < 10 ? '0'+minute : minute;
					}
					//44分钟调用强制提交
					if(minute>=44){
						uni.$emit('unlocking');
						count += 1;
						if(count==1){
							that.StopRunLimit();
							uni.$emit('changeState');
						}
					};
					if(minute>=60){
						minute=0;
						hour=parseInt(hour) +1;
						hour = hour < 10? '0'+hour : hour;
					}
					second = second < 10 ? '0' + second : second;
					that.time = hour+':'+minute+':'+second;
					var time = hour+':'+minute+':'+second;
					that.$store.commit("saveTime",time);
				};
				that.speedInt  = setInterval(()=>{
					var distance = that.$store.state.distance;
					that.runningDistance = (parseInt(distance)/1000).toFixed(2);
					var runTime = parseInt(hour)  +  parseInt(minute)/60  + parseInt(second)/3600 ;
					if(distance!=0){
						that.speed = ((distance/1000)/runTime).toFixed(2);
						let Info = {
							time : that.time,
							distance : distance,
							speed : that.speed
						}
						uni.setStorage({
							key: "statisticInfo",
							data: Info,
						});
					}else{
						that.speed = '0.00';
					}
				},1000)
			},
			/* 点击圆环进入跑步信息页  */
			runningTap(){
				if(this.isRunning == true){
					uni.navigateTo({
						url: 'running/running'
					});
				}else{
					uni.showToast({
						title: '请开始跑步后点击进入！',
						duration: 2000,
						icon: 'none'
					});
				}
			},
			/* 打开APP下载地址 */
			save(){
				plus.runtime.openURL('http://111.75.252.147:8083/Runing/app/Running.apk')
			},
			/* 45分钟强制提交跑步数据 */
			StopRunLimit(){
				const that = this;
				//截取时间的分钟
				var hour = parseInt(that.time.substring(0,2));
				var minute = parseInt(that.time.substring(3,5));
				var totalMinute = hour*60 + minute;
				var data = {
				    mileage: parseInt(that.runningDistance*1000),
				    runtime: that.time,
				    sid: userId.sid,
					wid: wid
				};
				homeApi.commitData(data).then(res => {
					uni.showLoading({
						title:"成绩上传中...",
					})
					setTimeout(()=>{
						if(res.data.code!=200){
							uni.hideLoading();
							uni.showToast({
								title: res.data.msg,
								duration: 2000,
								icon:"none"
							});
						}else{
							uni.hideLoading();
							that.initData();
							uni.showToast({
								title: "成绩上传成功",
								duration: 2000
							});
							uni.removeStorage({
							    key: 'statisticInfo'
							});
							that.$store.commit('cleanStatistic');
						}
						//数据初始化
						clearInterval(that.timeInt);
						var time = '00:00:00';
						that.$store.commit("saveTime",time);
						that.time = time;
						that.runningDistance = "0.00";
						that.speed = "0.00"
						var stopState =  true;
						that.$store.commit("saveStopState",stopState);
						that.isRunning = false;
						uni.$emit('stopLocate',{msg:"stopLocate"});
					},1000)
				}).catch(err=>{
					uni.showToast({
						//-----------------------------------------------------
						title: "数据提交失败，请重试或反馈!",
						icon:'none',
						duration:1500
						//-----------------------------------------------------
					})
				})
			},
			/* 获取最新通知 */
			notification(){
				const that = this;
				homeApi.getNotification().then(res=>{
					if(res.data.code===200){
						let notify = res.data.data.date;
						let Nindex = notify.length;
						let N_notID= notify[Nindex-1].mid;
						let Oindex = '';
						let O_notID= '';
						uni.getStorage({
							key:'allNotification',
							success(res){
								Oindex = res.data.length;
								O_notID = res.data[Oindex-1].mid;
								if(O_notID!==N_notID){
									uni.showModal({
										title: '最新消息通知',
										content: notify[Nindex-1].content,
										showCancel:false,
										success: function (res) {
											if (res.confirm) {
											}
										}
									});
									uni.setStorage({
										key:'allNotification',
										data:notify
									})
								}
							},
							fail() {
								uni.showModal({
									title: '最新消息通知',
									content: notify[Nindex-1].content,
									showCancel:false,
									success: function (res) {
										if (res.confirm) {
										}
									}
								});
								uni.setStorage({
									key:'allNotification',
									data:notify
								})
							}
						})
					}
				})
			},
			/* 加载缓存的跑步信息 */
			cacheLoading(){
				const that = this;
				uni.getStorage({
					key: 'statisticInfo',
					success(res) {
						that.time = res.data.time;
						that.runningDistance = ((res.data.distance)/1000).toFixed(2);
						let distance = res.data.distance;
						that.$store.commit("saveTime",res.data.time);
						that.$store.commit("saveDistance",distance);
						that.speed = res.data.speed;
					}
				})
			}
		}
	}
</script>

<style>
	.container {
		width: 100%;
		height: 100%;
		box-sizing: border-box;
	}
	
	.loading-indicator {
		position: absolute;
		width: 210px;
		height: 210px;
		margin: 100px calc(50% - 105px);
	}
	
	.loading-indicator:before {
		content: "";
		display: block;
		width: 210px;
		height: 105px;
		padding-bottom: 0;
		box-sizing: border-box;
		border-top-left-radius: 210px;
		border-top-right-radius: 210px;
		background: -webkit-linear-gradient(0deg, #6149f6, #3fecff);
	}
	
	.loading-indicator:after {
		content: "";
		display: block;
		width: 210px;
		height: 105px;
		padding-top: 0;
		box-sizing: border-box;
		border-bottom-left-radius: 210px;
		border-bottom-right-radius: 210px;
		background: -webkit-linear-gradient(0deg, #6149f6, #3fecff);
	}
	
	.loading-indicator>text {
		display: block;
		position: absolute;
		width: 200px;
		height: 200px;
		background: #FFFFFF;
		top: 5px;
		left: 5px;
		border-radius: 50%;
		z-index: 5;
	}
	
	.head-in {
		position: relative;
		width: 194px;
		height: 194px;
		margin: 0 auto;
		padding-top: 105px;
		text-align: center;
		border-radius: 50%;
		z-index: 99;
		box-sizing: border-box;
	}
	
	.run-count {
		display: block;
		padding-top: 45px;
		font-size: 48px;
		font-weight: 600;
	}
	
	.run-company {
		margin-left: 10px;
		margin-right: -5px;
		font-size: 20px;
	}
	
	.run-target {
		display: block;
		margin-top: 10px;
		font-size: 18px;
	}
	
	.main {
		display: flex;
		margin: 140px auto 0;
		padding: 0 5px;
		text-align: center;
	}
	
	.main view {
		flex: 1;
		height: 120px;
		margin: 5px;
		border-radius: 5px;
		border: 1px solid #1989fa;
		box-sizing: border-box;
	}
	
	.main>view>image {
		display: block;
		width: 32px;
		height: 32px;
		margin: 10px auto;
	}
	
	.main>view>text {
		display: block;
	}
	
	.main-time {
		flex: 1.4 !important;
	}
	
	.main-title {
		font-size: 14px;
	}
	
	.main-content {
		margin-top: 5px;
		font-size: 24px;
		font-weight: 600;
	}
	
	.foot {
		min-height: calc(100% - 465px);
		padding-top: 40px;
		box-sizing: border-box;
	}
	
	.foot-start {
		width: 150px;
		height: 150px;
		margin: auto auto;
		padding: 50px;
		background-color: #6495ed;
		border-radius: 50%;
		box-sizing: border-box;
	}
	
	.foot-start>image {
		display: block;
		width: 100%;
		height: 100%;
	}
	
	.up {
		position: absolute;
		top: 0;
		width: 100%;
		height: 100%;
		background-color: #FFFFFF;
		z-index: 9999999999999999999;
	}
	.popup {
		width: 80%;
		height: 150px;
		margin: calc(100% - 75px) auto 0 auto;
		background-color: #FFFFFF;
		border-radius: 5px;
		/* border: 1px solid #bdbdbd; */
	}
	.progress-body{
		padding: 10px 10px;
	}
</style>
